package cn.tedu.user.service;

import cn.tedu.user.controller.UserController;
import cn.tedu.user.mapper.UserMapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jt.common.pojo.User;
import com.jt.common.pojo.UserGithub;
import com.jt.common.utils.MD5Util;
import com.jt.common.utils.MSUtil;
import com.jt.common.utils.VerifyCode;
import com.jt.common.vo.SysResult;
import com.netflix.client.http.HttpResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.UUID;
import java.util.concurrent.TimeUnit;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Service
public class UserService {
    @Autowired(required = false)
    private UserMapper userMapper;

    public void sendMs(String phoneNum){
        String verify = VerifyCode.verify();
        MSUtil.sendMs(phoneNum,verify);
    }

    public boolean checkUserName(String userName) {
        int count = userMapper.selectCountByUsername(userName);
        return count==0;
    }

    public void doRegister(User user) {
        String userId = UUID.randomUUID().toString();
        user.setUserId(userId);
        user.setUserPassword(MD5Util.md5(user.getUserPassword()));
        userMapper.insertUser(user);
    }

    private static final ObjectMapper mapper=new ObjectMapper();
    @Autowired
    private StringRedisTemplate redisTemplate;

    public String doLogin(User user) throws JsonProcessingException {
        System.out.println(user.toString());
        ValueOperations<String, String> opsForValue = redisTemplate.opsForValue();
        ListOperations<String, String> opsForList = redisTemplate.opsForList();

        user.setUserPassword(MD5Util.md5(user.getUserPassword()));
        //通过持久层查询
        User exist = userMapper.selectExistByUsernameAndPassword(user);
        if (exist==null){
            return "";
        }else{
            //添加登录顶替
            String userLogin="login_"+user.getUserName();
            //顶替
            /*if (redisTemplate.hasKey(userLogin)) {
                redisTemplate.delete(opsForValue.get(userLogin));
            }*/
            //同时登陆2人
            if (opsForList.size(userLogin)>1){
                String s = opsForList.rightPop(userLogin);
                redisTemplate.delete(s);
            }

            String key = "EM_TICKET_"+System.currentTimeMillis()+user.getUserName();
            exist.setUserPassword(null);
            exist.setUserName(exist.getUserNickname());
            String value = mapper.writeValueAsString(exist);
            opsForValue.set(key,value,2, TimeUnit.HOURS);

            //opsForValue.set(userLogin,key,2,TimeUnit.HOURS);
            opsForList.leftPush(userLogin,key);

            return key;
        }
    }

    public String queryUserjson(String ticket) {
        ValueOperations<String, String> opsForValue = redisTemplate.opsForValue();
        String userLogin = "login_"+getUsername(ticket);
        Long leftTime = redisTemplate.getExpire(ticket);
        if (leftTime<1000*60*60){
            redisTemplate.expire(ticket,2,TimeUnit.HOURS);
            redisTemplate.expire(userLogin,2,TimeUnit.HOURS);
        }
        return opsForValue.get(ticket);
    }
    public String getUsername(String ticket){
        return ticket.substring(23);
    }

    public void logout(String ticket) {
        //String userLogin = "login_"+getUsername(ticket);
        //redisTemplate.delete(userLogin);
        redisTemplate.delete(ticket);
    }

    private String githubAuthUri="http://github.com/login/oauth/authorize";
    private String githubTokenUrl="https://github.com/login/oauth/access_token";
    private String clientId="cf291b0793ee77e8a6e8";
    private String clientSecret="7a7014ed061f3ecab3b72851612b8fa9f7feee35";
    private String githubUserUrl="https://api.github.com/user";

    public String githubLogin() {
        RestTemplate template = new RestTemplate();
        String url=githubAuthUri+"?client_id="+clientId;
        return "redirect:"+url;
    }

    @Autowired
    private UserController userController;



    public String getTokenAndResource(String code) throws JsonProcessingException {
        RestTemplate template = new RestTemplate();
        String url=githubTokenUrl+"?code={1}&client_id={2}&client_secret={3}";
        String body = template.postForObject(url, null, String.class, code, clientId, clientSecret);
        String token = getToken(body);
        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization","token "+token);
        HttpEntity entity = new HttpEntity(headers);
        //ResponseEntity<UserBean> response = template.exchange(githubUserUrl, HttpMethod.GET,entity,UserBean.class);
        //UserBean user = response.getBody();
        ResponseEntity<UserGithub> response = template.exchange(githubUserUrl, HttpMethod.GET,entity, UserGithub.class);
        UserGithub userGithub = response.getBody();
        System.out.println(userGithub.toString());
        User user = new User();
        if (!checkUserName(userGithub.getLogin())){
//            user.setUserName(userGithub.getLogin());
//            user.setUserPassword(userGithub.getId());
            User user1 = userMapper.selectExistByUsername(userGithub.getLogin());
            //String s = mapper.writeValueAsString(user1);
            user1.setUserPassword(userGithub.getId());
            //System.out.println(s);
            return doLogin(user1);
        }else{
            user.setUserId(UUID.randomUUID().toString());
            user.setUserName(userGithub.getLogin());
            user.setUserPassword(userGithub.getId());
            user.setUserNickname(userGithub.getLogin());
            user.setUserEmail(userGithub.getLogin()+"@github.com");
            doRegister(user);
            //String s = mapper.writeValueAsString(user);
            return doLogin(user);
           // return "redirect:localhost:10003/user/manage/login?"+s;
        }

    }

    public String getToken(String tokenStr){
        if (tokenStr!=null){
            return tokenStr.split("&")[0].split("=")[1];
        }
        return "";
    }
}
